import axios from "axios";
import memoryUtils from "./memoryUtils";
import { Message } from "element-ui";
import storageUtils from "./storageUtils";
import {Loading} from "element-ui"

const request = axios.create({
    baseURL:process.env.VUE_APP_BASE_API,
    timeout:5000
})

const loading={
    loadingInstance:null,
    open:function(){
        // console.log('加载中',this.loadingInstance);
        if(this.loadingInstance===null){
            // console.log('创建加载实例...');
            this.loadingInstance=Loading.service({
                text:'拼命加载中',
                target:'.main',
                background:'rgba(0,0,0,0.5)'
            })
        }
    },
    close:function(){
        if(this.loadingInstance!==null){
            this.loadingInstance.close()
            // console.log("加载结束");
        }
        this.loadingInstance = null
    }
}

const getMenus = ()=>{
   if(memoryUtils.user.role_id){
    const roleId = memoryUtils.user.role_id;
    const userMenus=memoryUtils.user.role.menus;
    console.log("usermenus",userMenus);
    request({
        url:`/menus`,
        method:'post',
        data:{roleId}
    }).then(res=>{
        const resp = res.data;
        if(resp.status == 0){
            const menus = resp.data.menus;
            console.log('menus',menus);
            if(userMenus.lenght ==menus.lenght){
                userMenus.forEach(item => {
                   if(menus.indexOf(item) == -1){
                    memoryUtils.user={};
                    storageUtils.removeUser();
                    Message({
                        message:"当前用户权限被修改，请重新登录",
                        type:"warning"
                    });
                    window.location.replace("/login")
                   }
                });
            }else{
                memoryUtils.user={};
                storageUtils.removeUser()
                Message({
                    message:"当前用户权限被修改，请重新登录",
                    type:"warning"
                })
                window.location.replace("/login")
            }
        }
        return
    }).catch(err=>{
        return
    })
   }
}

request.interceptors.request.use(config=>{
    
    if(config.url !=="/menus"){
        getMenus();
    }
    loading.open()
    return config
},error=>{
    loading.close()
    return Promise.reject(error)
})
request.interceptors.response.use(response=>{
    loading.close()
    const resp=response.data
    /* if(resp.status!=0){
        Message({
            message:resp.msg||'系统异常',
            type:'warning',
            duration:5000
        })
    } */
    return response
},err=>{
    loading.close()
    return Promise.reject(err)
})

export default request